<?php

use Medoo\Medoo;
use QL\QueryList;

/**
 * http://docs.guzzlephp.org/en/stable/request-options.html#query
 * https://medoo.in/api/new
 * http://www.querylist.cc/docs/guide/v4/http-client
 */
chdir(__DIR__);
require_once realpath('..') . '/vendor/autoload.php';
$config = include 'database.php';

echo '爬虫开始' . PHP_EOL;
$db = new Medoo($config);
const BRAND = '威马';
$db->delete('tDealer', ['sBrand' => BRAND]);
$client = new GuzzleHttp\Client(['timeout' => 0,]);


$res = $client->get('https://www.wm-motor.com/static/js/map.js');
$html = (string)$res->getBody();

$ok = preg_match('/arr_search = \[([\s\S]+?)\];/', $html, $m);
$dict = [];
$cities = json_decode(file_get_contents('cities.json'), true);
foreach ($cities as $row) {
    foreach ($row['citys'] as $city) {
        $dict[$city['citysName']] = $row['provinceName'];
    }
}

if ($ok) {
    $m[1] = trim($m[1]);
    $temp = '[' . substr($m[1], 0, strlen($m[1]) - 1) . ']';

    $dealers = json_decode($temp, true);
    foreach ($dealers as $item) {
        list($lng, $lat) = explode(',', $item[1]);
        $pos = mb_strpos($item[0], '威马');

        $city = mb_substr($item[0], 0, $pos);
        if (mb_substr($city, mb_strlen($city) - 1) !== '市') {
            $city .= '市';
        }


        $db->insert('tDealer', [
            'sDealerName' => trim($item[0]),
            'nBrandID' => '-1',
            'sBrand' => BRAND,
            'sProvince' => $dict[$city],
            'sCity' => $city,
            'sAddress' => '',
            'sSaleCall' => '',
            'sLatitude' => $lat,
            'sLongitude' => $lng,
            'dUpdateTime' => Medoo::raw('now()'),
            'sManufacturer' => BRAND,
            'sRemarks' => $item[6] . '-' . $item[4],
        ]);
        echo "{$item[0]}完成" . PHP_EOL;
    }
    echo '爬虫结束' . PHP_EOL;
}